﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RedemptoristRetreatCenter.DatabaseUtility;
using RedemptoristRetreatCenter.HelperUtility;

namespace RedemptoristRetreatCenter
{
    public partial class RetreatRegistration : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString.Count > 0)
                {
                    ConversionUtility conversion = new ConversionUtility();
                    populateFields(conversion.stringToInt(Request.QueryString["ID"]));
                }
                    if (Session["isAdmin"] != null && (bool)Session["isAdmin"] == true)
                    {
                        SubmitButton.Text = "Save";
                        setControlsEditable(true);
                    }
                    else
                    {
                        SubmitButton.Text = "Register";
                        setControlsEditable(false);
                    }

                
            }
        }

        /// <summary>
        /// retrieve schedule data and populate controls
        /// </summary>
        /// <param name="selectedAttendance"></param>
        private void populateFields(int selectedAttendance)
        {
            RetreatRegistrationUtility retreatRegistrationUtility = new RetreatRegistrationUtility();
            RetreatRegistrationInfo retreatRegistrationInfo = retreatRegistrationUtility.getRetreatAttendanceByAttendanceId(selectedAttendance);
            ConversionUtility converter = new ConversionUtility();

            if (retreatRegistrationInfo != null)
            {
                ListItem searchItem = new ListItem(retreatRegistrationInfo.attendeeName, retreatRegistrationInfo.userId.ToString());
                ddRegistrant.SelectedIndex = ddRegistrant.Items.IndexOf(searchItem);

                searchItem = new ListItem(retreatRegistrationInfo.roomTypeDesc, retreatRegistrationInfo.roomType);
                ddRoomType.SelectedIndex = ddRoomType.Items.IndexOf(searchItem);

                searchItem = new ListItem(converter.boolToYesNo(retreatRegistrationInfo.firstFloorRequired), converter.booleanToInt(retreatRegistrationInfo.firstFloorRequired).ToString());
                ddFirstFloor.SelectedIndex = ddFirstFloor.Items.IndexOf(searchItem);

                txtGroupName.Text = retreatRegistrationInfo.groupName;
                txtDietary.Text = retreatRegistrationInfo.dietaryNeeds;
                txtComment.Text = retreatRegistrationInfo.comment;
                txtRoomNumber.Text = retreatRegistrationInfo.roomAssignment;
                txtAmountPaid.Text = retreatRegistrationInfo.amountPaid.ToString();
                txtDiscountAmount.Text = retreatRegistrationInfo.discountAmount.ToString();
            }
        }

        /// <summary>
        /// set controls with data as being editable or not
        /// </summary>
        /// <param name="isEnabled"></param>
        private void setControlsEditable(bool isEnabled)
        {
            txtRoomNumber.Enabled = isEnabled;
            txtAmountPaid.Enabled = isEnabled;
            txtDiscountAmount.Enabled = isEnabled;
            ddRegistrant.Enabled = isEnabled;
            return;
        }

        protected void ddRoomType_OnLoad(object sender, EventArgs e)
        {
            ddRoomType.Items.Add(new ListItem("No Preference","NP"));
            ddRoomType.Items.Add(new ListItem("One Bed","1B"));
            ddRoomType.Items.Add(new ListItem("Two Beds","2B"));
        }

        protected void ddFirstFloor_OnLoad(object sender, EventArgs e)
        {
            ddFirstFloor.Items.Add(new ListItem("No", "0"));
            ddFirstFloor.Items.Add(new ListItem("Yes","1"));
        }

        protected void ddRegistrant_OnLoad(object sender, EventArgs e)
        {
            if (ddRegistrant.Items.Count == 0) // this fires everytime control is touched.  only need to load once
            {
                UserAccountUtility userAccountUtility = new UserAccountUtility();
                List<UserAccountInfo> userAccounts = userAccountUtility.getAllUserList();

                for (int cntr = 0; cntr < userAccounts.Count; cntr++)
                {
                    ddRegistrant.Items.Add(new ListItem(String.Format("{0} {1}", userAccounts[cntr].firstName, userAccounts[cntr].lastName), userAccounts[cntr].userId.ToString()));
                    if (userAccounts[cntr].username.ToUpper().Equals(getUsername().ToUpper()))
                    {
                        // set selection.  An admin will be able to change it
                        ddRegistrant.SelectedIndex = ddRegistrant.Items.Count-1; 
                    }
                }
            }
        }

        protected void Submit_Click(object sender, EventArgs e)
        {
            bool success;
            RetreatRegistrationInfo registrationInfo = new RetreatRegistrationInfo();
            ConversionUtility converter = new ConversionUtility();
           
            registrationInfo.scheduleId = converter.stringToInt(Request.QueryString["ID"]);
            registrationInfo.groupName = txtGroupName.Text;
            registrationInfo.roomAssignment = txtRoomNumber.Text;
            registrationInfo.roomType = ddRoomType.SelectedValue;
            registrationInfo.userId = converter.stringToInt(ddRegistrant.SelectedValue);
            registrationInfo.modifiedBy = getUsername();
            registrationInfo.firstFloorRequired = (ddRoomType.SelectedItem.Text.Equals("Yes"));  // evaluates to boolean
            registrationInfo.dietaryNeeds = txtDietary.Text;
            registrationInfo.comment = txtComment.Text;
            registrationInfo.amountPaid = converter.stringToDouble(txtAmountPaid.Text);
            registrationInfo.discountAmount = converter.stringToDouble(txtDiscountAmount.Text);

            if (registrationInfo.scheduleId.Equals("") || registrationInfo.groupName.Equals("")
                    || registrationInfo.firstFloorRequired.Equals(""))
            {
                success = false;
            }
            else
            {
                RetreatRegistrationUtility retreatUtility = new RetreatRegistrationUtility();
                success = retreatUtility.registerForRetreat(registrationInfo, getUsername());
            }

            if (success)
            {
                StatusMessage.Text = "Registration for the Retreat was a Success";
            }
            else
            {
                StatusMessage.Text = "Unable to register for retreat";
            }
        }

        private string getUsername()
        {
            if (Session["Username"] != null)
            {
                return Session["Username"].ToString();
            }
            else
            {
                return String.Empty;
            }
        }
    }
}